package utils

import (
"strings"
"time"
)

const (
	LAYOUT_YMD = "2006-01-02"
	LAYOUT_HMS = "15:04:05"
)

/**
字符串时间转时间戳
timeType m秒 h毫秒 w微妙 n纳秒
*/
func StrToTime(timeStr string) int64 {
	loc, _ := time.LoadLocation("Local")
	var time_layout string
	switch len(timeStr) {
	case 19:
		time_layout = LAYOUT_YMD + " " + LAYOUT_HMS
	case 15:
		time_layout = strings.Replace(LAYOUT_YMD,"-","",-1) + strings.Replace(LAYOUT_HMS,":","",-1)
	case 10:
		time_layout = LAYOUT_YMD
	case 8:
		time_layout = strings.Replace(LAYOUT_YMD,"-","",-1)
	}
	theTime, _ := time.ParseInLocation(time_layout, timeStr, loc)
	return theTime.Unix()
}


/**
时间戳转字符时间
timeStamp 时间戳 如果为0 则返回当前时间
layout 字符串时间格式 如：YmdHis
 */
func TimeToStr(timeStamp int64, layout string) string {
	if	strings.Contains(layout, "Y"){
		layout = strings.Replace(layout, "Y", "2006", -1)
	}
	if strings.Contains(layout, "y"){
		layout = strings.Replace(layout, "y", "06", -1)
	}
	if strings.Contains(layout, "m"){
		layout = strings.Replace(layout, "m", "01", -1)
	}
	if strings.Contains(layout, "d"){
		layout = strings.Replace(layout, "d", "02", -1)
	}
	if strings.Contains(layout, "H"){
		layout = strings.Replace(layout, "H", "15", -1)
	}
	if strings.Contains(layout, "i"){
		layout = strings.Replace(layout, "i", "04", -1)
	}
	if strings.Contains(layout, "s"){
		layout = strings.Replace(layout, "s", "05", -1)
	}
	if timeStamp == 0 {
		return time.Now().Format(layout)
	} else {
		return time.Unix(timeStamp, 0).Format(layout)
	}
}
